package com.bookrecomm.service.impl;

import com.bookrecomm.dao.BookRepository;
import com.bookrecomm.dao.ReadHistoryRepository;
import com.bookrecomm.dao.UserRepository;
import com.bookrecomm.entity.Book;
import com.bookrecomm.entity.ReadHistory;
import com.bookrecomm.entity.User;
import com.bookrecomm.service.BookService;
import com.bookrecomm.service.ReadHistoryService;
import com.bookrecomm.vo.BookBriefVO;
import com.bookrecomm.vo.BookVO;
import com.bookrecomm.vo.PageVO;
import com.bookrecomm.vo.ReadHistoryVO;
import com.bookrecomm.vo.UserBriefVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 阅读历史服务实现类
 * 实现阅读历史相关的业务逻辑
 */
@Service
public class ReadHistoryServiceImpl implements ReadHistoryService {

    @Autowired
    private ReadHistoryRepository readHistoryRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private BookService bookService;

    /**
     * 添加或更新阅读历史
     * @param userId 用户ID
     * @param bookId 图书ID
     * @param progress 阅读进度（0-100）
     * @return 是否添加或更新成功
     */
    @Override
    @Transactional
    public boolean addOrUpdateReadHistory(Long userId, Long bookId, Integer progress) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            userId = user.getId();
        }

        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 检查图书是否存在
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new RuntimeException("图书不存在"));

        // 检查阅读进度是否合法
        if (progress < 0) {
            progress = 0;
        } else if (progress > 100) {
            progress = 100;
        }

        // 查询是否存在阅读历史
        ReadHistory readHistory = readHistoryRepository.findByUser_IdAndBook_Id(userId, bookId)
                .orElse(null);

        if (readHistory == null) {
            // 创建新的阅读历史
            readHistory = new ReadHistory();
            readHistory.setUserId(userId);
            readHistory.setBookId(bookId);
            readHistory.setProgress(progress);
            readHistory.setLastReadTime(LocalDateTime.now());
            readHistory.setCreatedAt(LocalDateTime.now());
            readHistory.setUpdatedAt(LocalDateTime.now());

            // 更新用户阅读数
            user.setReadCount(user.getReadCount() + 1);
            userRepository.save(user);

            // 更新图书阅读数
            book.setReadCount(book.getReadCount() + 1);
            bookRepository.save(book);
        } else {
            // 更新阅读历史
            readHistory.setProgress(progress);
            readHistory.setLastReadTime(LocalDateTime.now());
            readHistory.setUpdatedAt(LocalDateTime.now());

            // 如果阅读进度为100%，且之前未完成，则更新用户和图书的完成数
            if (progress == 100 && readHistory.getProgress() < 100) {
                user.setFinishCount(user.getFinishCount() + 1);
                userRepository.save(user);

                book.setFinishCount(book.getFinishCount() + 1);
                bookRepository.save(book);
            }
        }

        // 保存阅读历史
        readHistoryRepository.save(readHistory);

        return true;
    }

    /**
     * 获取用户的阅读历史列表
     * @param userId 用户ID
     * @param pageable 分页参数
     * @return 分页阅读历史列表
     */
    @Override
    public PageVO<ReadHistoryVO> getUserReadHistory(Long userId, Pageable pageable) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            userId = user.getId();
        }

        // 检查用户是否存在
        userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 查询阅读历史
        Page<ReadHistory> readHistoryPage = readHistoryRepository.findByUserId(userId, pageable);

        // 转换为VO对象
        List<ReadHistoryVO> readHistoryVOs = readHistoryPage.getContent().stream()
                .map(this::convertToReadHistoryVO)
                .collect(Collectors.toList());

        // 创建分页VO对象
        PageVO<ReadHistoryVO> pageVO = new PageVO<>();
        pageVO.setContent(readHistoryVOs);
        pageVO.setTotalElements(readHistoryPage.getTotalElements());
        pageVO.setTotalPages(readHistoryPage.getTotalPages());
        pageVO.setSize(readHistoryPage.getSize());
        pageVO.setNumber(readHistoryPage.getNumber());

        return pageVO;
    }

    /**
     * 获取用户最近阅读的图书列表
     * @param userId 用户ID
     * @param limit 限制数量
     * @return 最近阅读的图书列表
     */
    @Override
    public PageVO<BookVO> getRecentlyRead(Long userId, int limit) {
        // 定义最终使用的用户ID变量
        final Long finalUserId;
        
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                // 未登录，返回空列表
                PageVO<BookVO> pageVO = new PageVO<>();
                pageVO.setContent(List.of());
                pageVO.setTotalElements(0L);
                pageVO.setTotalPages(0);
                pageVO.setSize(limit);
                pageVO.setNumber(0);
                return pageVO;
            }
            
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElse(null);
            if (user == null) {
                // 用户不存在，返回空列表
                PageVO<BookVO> pageVO = new PageVO<>();
                pageVO.setContent(List.of());
                pageVO.setTotalElements(0L);
                pageVO.setTotalPages(0);
                pageVO.setSize(limit);
                pageVO.setNumber(0);
                return pageVO;
            }
            finalUserId = user.getId();
        } else {
            finalUserId = userId;
        }

        // 查询最近阅读的图书
        Pageable pageable = PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "lastReadAt"));
        Page<ReadHistory> readHistoryPage = readHistoryRepository.findByUserId(finalUserId, pageable);

        // 获取图书ID列表
        List<Long> bookIds = readHistoryPage.getContent().stream()
                .map(ReadHistory::getBookId)
                .collect(Collectors.toList());

        // 查询图书详情
        List<Book> books = bookRepository.findAllById(bookIds);

        // 按照阅读顺序排序
        List<Book> sortedBooks = bookIds.stream()
                .map(id -> books.stream()
                        .filter(book -> book.getId().equals(id))
                        .findFirst()
                        .orElse(null))
                .filter(book -> book != null)
                .collect(Collectors.toList());

        // 转换为VO对象
        List<BookVO> bookVOs = sortedBooks.stream()
                .map(book -> bookService.convertToBookVO(book, finalUserId))
                .collect(Collectors.toList());

        // 创建分页VO对象
        PageVO<BookVO> pageVO = new PageVO<>();
        pageVO.setContent(bookVOs);
        pageVO.setTotalElements(readHistoryPage.getTotalElements());
        pageVO.setTotalPages(readHistoryPage.getTotalPages());
        pageVO.setSize(readHistoryPage.getSize());
        pageVO.setNumber(readHistoryPage.getNumber());

        return pageVO;
    }

    /**
     * 获取用户的阅读进度
     * @param userId 用户ID
     * @param bookId 图书ID
     * @return 阅读进度（0-100）
     */
    @Override
    public Integer getReadProgress(Long userId, Long bookId) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return 0; // 未登录
            }
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElse(null);
            if (user == null) {
                return 0; // 用户不存在
            }
            userId = user.getId();
        }

        // 查询阅读历史
        ReadHistory readHistory = readHistoryRepository.findByUser_IdAndBook_Id(userId, bookId)
                .orElse(null);

        return readHistory != null ? readHistory.getProgress() : 0;
    }

    /**
     * 删除阅读历史
     * @param userId 用户ID
     * @param bookId 图书ID
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public boolean deleteReadHistory(Long userId, Long bookId) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            userId = user.getId();
        }

        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 检查图书是否存在
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new RuntimeException("图书不存在"));

        // 查询阅读历史
        ReadHistory readHistory = readHistoryRepository.findByUser_IdAndBook_Id(userId, bookId)
                .orElse(null);

        if (readHistory == null) {
            return true; // 不存在，直接返回成功
        }

        // 删除阅读历史
        readHistoryRepository.delete(readHistory);

        // 更新用户阅读数
        if (user.getReadCount() > 0) {
            user.setReadCount(user.getReadCount() - 1);
        }

        // 如果阅读进度为100%，则更新用户完成数
        if (readHistory.getProgress() == 100 && user.getFinishCount() > 0) {
            user.setFinishCount(user.getFinishCount() - 1);
        }

        userRepository.save(user);

        // 更新图书阅读数
        if (book.getReadCount() > 0) {
            book.setReadCount(book.getReadCount() - 1);
        }

        // 如果阅读进度为100%，则更新图书完成数
        if (readHistory.getProgress() == 100 && book.getFinishCount() > 0) {
            book.setFinishCount(book.getFinishCount() - 1);
        }

        bookRepository.save(book);

        return true;
    }

    /**
     * 清空用户的阅读历史
     * @param userId 用户ID
     * @return 是否清空成功
     */
    @Override
    @Transactional
    public boolean clearReadHistory(Long userId) {
        // 定义最终使用的用户ID变量
        final Long finalUserId;
        
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            finalUserId = user.getId();
        } else {
            finalUserId = userId;
        }

        // 检查用户是否存在
        User user = userRepository.findById(finalUserId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 查询用户的阅读历史
        List<ReadHistory> readHistories = readHistoryRepository.findAllByUser_Id(finalUserId);

        // 更新图书阅读数和完成数
        for (ReadHistory readHistory : readHistories) {
            Book book = bookRepository.findById(readHistory.getBookId())
                    .orElse(null);
            if (book != null) {
                if (book.getReadCount() > 0) {
                    book.setReadCount(book.getReadCount() - 1);
                }
                if (readHistory.getProgress() == 100 && book.getFinishCount() > 0) {
                    book.setFinishCount(book.getFinishCount() - 1);
                }
                bookRepository.save(book);
            }
        }

        // 删除所有阅读历史
        readHistoryRepository.deleteAllByUser_Id(finalUserId);

        // 更新用户阅读数和完成数
        user.setReadCount(0L);
        user.setFinishCount(0L);
        userRepository.save(user);

        return true;
    }

    /**
     * 获取用户阅读历史数量
     * @param userId 用户ID
     * @return 阅读历史数量
     */
    @Override
    public Long countUserReadHistory(Long userId) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return 0L; // 未登录
            }
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElse(null);
            if (user == null) {
                return 0L; // 用户不存在
            }
            userId = user.getId();
        }

        return readHistoryRepository.countByUser_Id(userId);
    }

    /**
     * 将阅读历史实体转换为VO对象
     * @param readHistory 阅读历史实体
     * @return 阅读历史VO对象
     */
    private ReadHistoryVO convertToReadHistoryVO(ReadHistory readHistory) {
        ReadHistoryVO readHistoryVO = new ReadHistoryVO();
        BeanUtils.copyProperties(readHistory, readHistoryVO);

        // 设置用户信息
        User user = userRepository.findById(readHistory.getUserId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        UserBriefVO userBriefVO = new UserBriefVO();
        userBriefVO.setId(user.getId());
        userBriefVO.setUsername(user.getUsername());
        userBriefVO.setNickname(user.getNickname());
        userBriefVO.setAvatar(user.getAvatar());
        readHistoryVO.setUser(userBriefVO);

        // 设置图书信息
        Book book = bookRepository.findById(readHistory.getBookId())
                .orElseThrow(() -> new RuntimeException("图书不存在"));
        BookBriefVO bookBriefVO = new BookBriefVO();
        bookBriefVO.setId(book.getId());
        bookBriefVO.setTitle(book.getTitle());
        bookBriefVO.setCoverUrl(book.getCoverUrl());
        bookBriefVO.setAuthor(book.getAuthor());
        readHistoryVO.setBook(bookBriefVO);

        return readHistoryVO;
    }
}
